<?php
namespace x_mier\eases;

use think\facade\Db;

class Base
{
    //查询数据库所有表信息
    public static function tables()
    {
        $tables = Db::query('show table status');
        return $tables;
    }
    //查询表信息
    public function table($table)
    {
        $database = config('database.connections.mysql.database');
        $res = Db::query("select table_comment from information_schema.tables where table_schema = '$database' and table_name ='$table'");
        return $res[0]['table_comment'];
    }
    //查询表中所有字段信息
    public function columns($table)
    {
        $columns = Db::query("SHOW FULL COLUMNS FROM " . $table);
        return $columns;
    }
    //查询主键名称
    public function column_name($table)
    {
        $res = Db::query("SELECT COLUMN_NAME AS zj FROM INFORMATION_SCHEMA. COLUMNS WHERE TABLE_NAME= '$table' AND COLUMN_KEY = 'PRI'");
        return $res[0]['zj'];
    }
    //获取模块
    public function mokuai()
    {
        $dir = dirname(dirname(dirname(__FILE__)));
        $files = array();
        if (is_dir($dir)) {
            $child_dirs = scandir($dir);
            foreach ($child_dirs as $child_dir) {
                if ($child_dir != '.' && $child_dir != '..' && $child_dir != "extra" && !strstr($child_dir, '.')) {
                    $files[] = $child_dir;
                }
            }
        }
        foreach ($files as $k => $v) {
            if ('code' == $v || 'http' == $v) {
                unset($files[$k]);
            }
        }
        return $files;
    }

    // //生成文件的数据
    public function validatabuild($mokuai, $modelLayer, $table = null)
    {
        $data[$mokuai] = [
            '__dir__' => [$modelLayer],
            "$modelLayer" => [$table],
        ];
        return $data;
    }
    /**
     * 验证器开始
     * @param  [type] $c [description]
     * @return [type]    [description]
     */
    //数据表名转换成符合命名规格的字符串
    public static function parseName($name, $type = 0, $ucfirst = true)
    {
        if ($type) {
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                return strtoupper($match[1]);
            }, $name);
            return $ucfirst ? ucfirst($name) : lcfirst($name);
        }

        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
    }
    public function _getf($c)
    {
        if ($c['Comment'] != '') {
            return $c['Comment'];
        } else {
            return $c['Field'];
        }

    }
    public function _name($k, $name, $value)
    {
        if (empty($name)) {
            $data = $this->_getf($k) . $value;
        } else {
            $data = $name . $value;
        }
        return $data;
    }
    //验证代码
    public function validatas($cls, $vals)
    {
        $ms = array();
        $rs = array();
        $ss = array();
        for ($k = 0; $k < count($cls); $k++) {
            $c = $cls[$k]['Field'];
            if (isset($vals[$c])) {
                if ($vals[$c] == 'on') {
                    $ss[] = $c;
                }
            }
            if (isset($vals[$c . '_' . 'require'])) {
                if ($vals[$c . '_' . 'require'] == 'on') {
                    $rs[$c][] = 'require';
                    $ms[$c . '.require'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '必填');
                }
            }
            if (isset($vals[$c . '_' . 'number'])) {
                if ($vals[$c . '_' . 'number'] == 'on') {
                    $rs[$c][] = 'number';
                    $ms[$c . '.number'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为数字');
                }
            }
            if (isset($vals[$c . '_' . 'float'])) {
                if ($vals[$c . '_' . 'float'] == 'on') {
                    $rs[$c][] = 'float';
                    $ms[$c . '.float'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为小数');
                }
            }
            if (isset($vals[$c . '_' . 'boolean'])) {
                if ($vals[$c . '_' . 'boolean'] == 'on') {
                    $rs[$c][] = 'boolean';
                    $ms[$c . '.boolean'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为布尔');
                }
            }
            if (isset($vals[$c . '_' . 'email'])) {
                if ($vals[$c . '_' . 'email'] == 'on') {
                    $rs[$c][] = 'email';
                    $ms[$c . '.email'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为邮箱格式');
                }
            }
            if (isset($vals[$c . '_' . 'accepted'])) {
                if ($vals[$c . '_' . 'accepted'] == 'on') {
                    $rs[$c][] = 'accepted';
                    $ms[$c . '.accepted'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为是和否');
                }
            }
            if (isset($vals[$c . '_' . 'date'])) {
                if ($vals[$c . '_' . 'date'] == 'on') {
                    $rs[$c][] = 'date';
                    $ms[$c . '.date'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为日期');
                }
            }
            if (isset($vals[$c . '_' . 'alpha'])) {
                if ($vals[$c . '_' . 'alpha'] == 'on') {
                    $rs[$c][] = 'alpha';
                    $ms[$c . '.alpha'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为字母');
                }
            }
            if (isset($vals[$c . '_' . 'array'])) {
                if ($vals[$c . '_' . 'array'] == 'on') {
                    $rs[$c][] = 'array';
                    $ms[$c . '.array'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为数组');
                }
            }
            if (isset($vals[$c . '_' . 'alphaNum'])) {
                if ($vals[$c . '_' . 'alphaNum'] == 'on') {
                    $rs[$c][] = 'alphaNum';
                    $ms[$c . '.alphaNum'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为字母数字');
                }
            }
            if (isset($vals[$c . '_' . 'alphaDash'])) {
                if ($vals[$c . '_' . 'alphaDash'] == 'on') {
                    $rs[$c][] = 'alphaDash';
                    $ms[$c . '.alphaDash'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为字母数字下划线等');

                }
            }
            if (isset($vals[$c . '_' . 'chs'])) {
                if ($vals[$c . '_' . 'chs'] == 'on') {
                    $rs[$c][] = 'chs';
                    $ms[$c . '.chs'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为汉字');

                }
            }
            if (isset($vals[$c . '_' . 'chsAlpha'])) {
                if ($vals[$c . '_' . 'chsAlpha'] == 'on') {
                    $rs[$c][] = 'chsAlpha';
                    $ms[$c . '.chsAlpha'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为汉字字母等');

                }
            }
            if (isset($vals[$c . '_' . 'chsAlphaNum'])) {
                if ($vals[$c . '_' . 'chsAlphaNum'] == 'on') {
                    $rs[$c][] = 'chsAlphaNum';
                    $ms[$c . '.chsAlphaNum'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为汉字字母数字等');

                }
            }
            if (isset($vals[$c . '_' . 'chsDash'])) {
                if ($vals[$c . '_' . 'chsDash'] == 'on') {
                    $rs[$c][] = 'chsDash';
                    $ms[$c . '.chsDash'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为汉字字母数字破折号下划线等');

                }
            }

            if (isset($vals[$c . '_' . 'activeUrl'])) {
                if ($vals[$c . '_' . 'activeUrl'] == 'on') {
                    $rs[$c][] = 'activeUrl';
                    $ms[$c . '.activeUrl'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为域名/IP');

                }
            }
            if (isset($vals[$c . '_' . 'url'])) {
                if ($vals[$c . '_' . 'url'] == 'on') {
                    $rs[$c][] = 'url';
                    $ms[$c . '.url'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为URL');
                }
            }
            if (isset($vals[$c . '_' . 'ip'])) {
                if ($vals[$c . '_' . 'ip'] == 'on') {
                    $rs[$c][] = 'ip';
                    $ms[$c . '.ip'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为ip');

                }
            }
            if (isset($vals[$c . '_' . 'phone'])) {
                if ($vals[$c . '_' . 'phone'] == 'on') {
                    $rs[$c][] = 'regex:/^1[345789]\d{9}$/';
                    $ms[$c . '.phone'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为手机号格式');
                }
            }
            if (isset($vals[$c . '_' . 'shen'])) {
                if ($vals[$c . '_' . 'shen'] == 'on') {
                    $rs[$c][] = 'regex:/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/i';
                    $ms[$c . '.shen'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '为身份证格式');
                }
            }
            if (isset($vals[$c . '_' . 'regex'])) {
                if ($vals[$c . '_' . 'regex'] != '') {
                    $rs[$c][] = 'regex:' . $vals[$c . '_' . 'regex'];
                    $ms[$c . '.regex'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '无法通过验证');
                }
            }
            if (isset($vals[$c . '_' . 'confirm'])) {
                if ($vals[$c . '_' . 'confirm'] != '') {
                    $rs[$c][] = 'confirm:' . $vals[$c . '_' . 'confirm'];
                    $ms[$c . '.confirm'] = $this->_name($cls[$k], '和' . $vals[$c . '_' . 'confirm'], '不一致');
                }
            }
            if (isset($vals[$c . '_' . 'max'])) {
                if ($vals[$c . '_' . 'max'] != '') {
                    $rs[$c][] = 'max:' . $vals[$c . '_' . 'max'];
                    $ms[$c . '.max'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '最大值为' . $vals[$c . '_' . 'max']);

                }
            }
            if (isset($vals[$c . '_' . 'min'])) {
                if ($vals[$c . '_' . 'min'] != '') {
                    $rs[$c][] = 'min:' . $vals[$c . '_' . 'min'];
                    $ms[$c . '.min'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '最小值为' . $vals[$c . '_' . 'min']);
                }
            }
            if (isset($vals[$c . '_' . 'before'])) {
                if ($vals[$c . '_' . 'before'] != '') {
                    $rs[$c][] = 'before:' . $vals[$c . '_' . 'before'];
                    $ms[$c . '.before'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '必须在' . $vals[$c . '_' . 'before'] . '之前');
                }
            }
            if (isset($vals[$c . '_' . 'after'])) {
                if ($vals[$c . '_' . 'after'] != '') {
                    $rs[$c][] = 'after:' . $vals[$c . '_' . 'after'];
                    $ms[$c . '.after'] = $this->_name($cls[$k], $vals[$c . '_' . 'name'], '必须在' . $vals[$c . '_' . 'before'] . '之后');
                }
            }
        }
        $data = [
            'rs' => $rs,
            'ms' => $ms,
            'ss' => $ss,
        ];
        return $data;
    }
    //验证器生成文件代码
    public function validatacode($mokuai, $name, $data, $fields)
    {
        $txt = "<?php
namespace app\\$mokuai\\validate;

use think\\Validate;

class $name extends Validate
{
    protected \$rule = [
    ";
        foreach ($data['rs'] as $k => $v) {
            $txt .= "    '$k' => '" . implode('|', $v) . "',
    ";
        }
        $txt .= "
    ];
    protected \$message = [
    ";
        foreach ($data['ms'] as $k => $v) {
            $txt .= "    '$k' => '$v',
    ";
        }
        $txt .= "
    ];
    protected \$scene = [
        'add'   =>  [$fields],
        'edit'  =>  [$fields],

    ];
}";
        return $txt;
    }
    /**
     * 验证器结束
     */
    //生成控制器模型视图的数据
    public function cbuild($mokuai, $name, $mkname)
    {
        $data[$mokuai] = [
            '__dir__' => ['controller'],
            $name => [$mkname],
        ];
        return $data;
    }
    public function ViewCode($mokuai)
    {
        $file = 'config/template/' . $mokuai . '/base.tpl';
        $txt = file_get_contents($file);
        // dump($txt);die;
        return $txt;
    }

    /**
     * 列表
     */
    public function lst_code($path, $name, $table)
    {
        if (empty($path) || empty($name) || empty($table)) {
            return false;
        }
        $name = $name . '.html';
        $cls = $this->columns($table);
        $val = '';
        foreach ($cls as $k => $v) {
            if ($v['Field'] == 'status') {
                $val .= "                , {field: 'status',width: 100, title: '状态', align: 'center', templet: '#staBar'}\n";
            } else if ($v['Field'] == 'id' || $v['Field'] == 'is_del' || $v['Field'] == 'password') {

            } else {
                if ($k) {
                    if (count($cls) == $k + 1) {
                        $val .= "                , {field: '" . $v['Field'] . "', width: '', title: '" . $v['Comment'] . "', align: 'center'}";
                    } else {
                        $val .= "                , {field: '" . $v['Field'] . "', width: '', title: '" . $v['Comment'] . "', align: 'center'}\n";
                    }
                }
            }

        }
        $txt = <<<EOF
<table id="lst" lay-filter="demo"></table>
<script type="text/html" id="toolbar">
<div class="layui-btn-container">
<div class="mier-table-tool-row layui-row">
    <ul class="mier-table-tool-ul">
        {include file="public/tool" /}
        <div class="layui-btn table-tool-input layui-col-md2">
            <input type="text" class="layui-input layui-btn-sm" name="key" placeholder="输入需查询的标题/名称"/>
        </div>
        <button class="layui-btn layui-btn-sm" lay-submit="" lay-filter="search">检索</button>
    </ul>
</div>
</div>
</script>
<!--操作模板-->
<script type="text/html" id="opeBar">
    <a class="layui-btn layui-btn-xs" mier-event="info" data-url="{:url('edit')}" data-id="{{d.id}}"><i class="layui-icon layui-icon-edit"></i>编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>
<!--状态模板-->
<script type="text/html" id="staBar">
    <input type="checkbox" value="{{d.id}}" lay-skin="switch" lay-text="ON|OFF" lay-filter="OnOff"{{ d.status == 1 ? "checked" : "" }}  >
</script>
<script>
    layui.use(['table','form','system'], function () {
        var $ = layui.$
            , form = layui.form
            , table = layui.table;
        var tableIns = table.render({
            elem: "#lst"
            , url: "{:url('lst')}"
            , page: true
            , autoSort: false
            , method: "post"
            , limits: "{:config_group('limits')}"
            , limit: "{:config_group('pages')}"
            , loading: true
            , toolbar: "#toolbar"
            , cols: [[
                {type: 'checkbox'}
                , {type:'numbers', width: 80, title: '序号'}
{$val}
                , {width: 150, title: '操作', align: 'center', toolbar: '#opeBar'}
            ]]
        });
        //监听头工具栏检索事件
        form.on('submit(search)',function(data){
            // var data=data.field;
            tableIns.reload({
                where: data.field
                ,page: {curr: 1}
            })
        });
        //监听工具条
        table.on('tool(demo)', function(obj){
            var id = obj.data.id; //获得当前行数据
            if(obj.event === 'del'){ //删除
            layer.confirm('确定删除行吗？此操作不可逆！',{skin: 'layui-layer-molv',icon: 3, title:'删除提示'},function(){
                Api_Post({id:id},"{:url('del')}");
            });
            }
        });
        //监听单元格编辑
        table.on('edit(demo)', function (obj) {
            var data = {
                id: obj.data.id,
                [obj.field]:obj.value
            }
            Api_Post(data, "{:url('edit')}");
        });
        //监听状态开关操作
        form.on('switch(OnOff)', function (obj) {
            var num = obj.elem.checked == true? 1: 0;
            Api_Post({id:obj.value,status:num},"{:url('status')}");
        });
        //关闭后回调函数
        $(function(){
            function tab_close(v) {
                tableIns.reload({page: {curr: 1}});
            }
            window.pages_close=tab_close; //开放一个接口给window
        });
    });
</script>
EOF;
        return add_dir_file($path, $name, $txt);
    }
    //控制器
    public function conller_code($path, $mokuai, $table)
    {
        if (empty($path) || empty($mokuai)) {
            return false;
        }
        $Mokuai = $mokuai;
        $name = $Mokuai . '.php';
        $x_mokuai = strtolower($Mokuai);
        $txt = <<<EOF
<?php
namespace app\system\controller;
use app\system\model\\{$Mokuai} as {$Mokuai}Model;
use think\\facade\Db;
use think\\facade\View;
class {$Mokuai} extends Common
{
    /**
        * 列表
    */
    public function lst(){
        if (request()->isPost()) {
            \${$x_mokuai} = new {$Mokuai}Model;
            \$limit = input('limit');
            \$data=\${$x_mokuai}->getAll(\$limit);
            return tocode(0,"成功",\$data->items(),\$data->total());
        }
        return view();
    }
    /**
        * 添加提交
    */
    public function add(){
        \${$x_mokuai} = new {$Mokuai}Model;
        if (request()->isPost()) {
            \$data = input('post.');
            if(empty(\$data)){
                return tocode(100,'数据不能为空');
            }
            \$info = \${$x_mokuai}->info(\$data);
            if(!\$info){
                return tocode(100,'添加失败');
            }
            return tocode(200,'添加成功！');
        }
        {$this->is_type_id($table)}
    }
    /**
        * 修改提交
    */
    public function edit(){
        \${$x_mokuai} = new {$Mokuai}Model;
        if (request()->isAjax()) {
            \$id = input('id');
            if(empty(\$id)){
                return tocode(100,'ID不能为空');
            }
            if (request()->isPost()) {
                \$data = input('post.');
                if(empty(\$data)){
                    return tocode(100,'数据不能为空');
                }
                \$info = \${$x_mokuai}->info(\$data);
                if(!\$info){
                    return tocode(100,'编辑失败');
                }
                return tocode(200,'编辑成功！');
            }
            \$res = \${$x_mokuai}->getOne(\$id);
            {$this->is_images($table,3)}
            return tocode(200, 'ok', \$res);
        }
        {$this->is_type_id($table)}
    }
    /**
        * 状态
        */
    public function status()
    {
        if (request()->isPost()) {
            \$id=input('id');
            \$status=input('status');
            if(empty(\$id)){
                return tocode(100,'ID不能为空');
            }
            if(empty(\$status)){
                \$status = 0;
            }
            \${$x_mokuai} = new {$Mokuai}Model;
            \$status = \${$x_mokuai}->status(\$id,\$status);
            if(!\$status){
                return tocode(100,'修改状态失败');
            }
            return tocode(200,'修改状态成功！');
        }
    }
    /**
        * 删除单条
    */
    public function del(){
        \${$x_mokuai} = new {$Mokuai}Model;
        if (request()->isAjax()) {
            \$id = input('id');
            if(empty(\$id)){
                return tocode(100,'ID不能为空');
            }
            \$del = \${$x_mokuai}->del(\$id);
            if(!\$del){
                return tocode(100,'删除失败');
            }
            return tocode(200,'删除成功！');
        }
    }
    /**
        * 批量启用、禁用、删除
        */
    public function handleAll(){
        \$ids=input('id');
        \$type=input('type',0);
        if(empty(\$ids)){
            return tocode(100,'ID不能为空');
        }
        if(empty(\$type)){
            \$type = 0;
        }
        \${$x_mokuai} = new {$Mokuai}Model();
        \$all = \${$x_mokuai}->handleAll(\$ids,\$type);
        switch (\$type) {
            case '1':
                \$name = '启用';
                break;
            case '2':
                \$name = '删除';
                break;
            default:
                \$name = '禁用';
                break;
        }
        if(!\$all){
            return tocode(100,\$name.'失败');
        }
        return tocode(200,\$name.'成功！');
    }
}
EOF;
        return add_dir_file($path, $name, $txt);
    }
    // 模型
    public function model_code($path, $mokuai)
    {
        if (empty($path) || empty($mokuai)) {
            return false;
        }
        $Mokuai = $mokuai;
        $name = $Mokuai . '.php';
        $x_mokuai = strtolower($Mokuai);
        $txt = <<<EOF
<?php
namespace app\system\model;
use think\\Model;
use think\\facade\Db;
class {$Mokuai} extends Model
{
    /**
        * 根据条件获取配置列表信息
        */
    public function getAll(\$limit,\$start_time=false,\$end_time=false,\$key=false,\$map=[])
    {
        if (!empty(\$start_time) && empty(\$end_time)) {
            \$star_time = strtotime(\$start_time);
            \$map[] =['a.create_time','between',[\$star_time, time()]];
        }
        if (!empty(\$start_time) && !empty(\$end_time)) {
            \$star_time = strtotime(\$start_time);
            \$end_time = strtotime(\$end_time);
            \$map[] =['a.create_time','between',[\$star_time, \$end_time]];
        }
        if (!empty(\$key)) {
            \$map[] =['title|type','like',"%" . \$key . "%"];
        }
        \$res=\$this
        ->alias('a')
        ->where(\$map)
        ->paginate(\$limit);
        return \$res;
    }
    /**
        * 添加/编辑信息
        */
    public function info(\$param)
    {
        if (!empty(\$param['id'])) {
            \$res=\$this::find(\$param['id']);
        }else{
            \$res=\$this;
        }
        try {
            \$res->save(\$param);
        } catch (\Exception \$e) {
            return false;
        }
        return true;
    }
    /**
        * 根据id获取配置信息
        * @param \$id
        */
    public function getOne(\$id)
    {
        return \$this->where('id', \$id)->find();
    }

    /**
        * 状态切换
        */
    public function status(\$id,\$status){
        try {
            \$this->where('id',\$id)->update(['status'=>\$status]);
        } catch (\Exception \$e) {
            return false;
        }
        return true;
    }
    /**
        * 删除
        */
    public function del(\$id){
        try{
            \$this->where('id',\$id)->delete();
        }catch( \Exception \$e){
            return tocode(100,'删除失败');
        }
        return tocode(200,'删除成功');
    }

    /**
        * 批量操作
        */
    public function handleAll(\$param,\$type=0){
        try{
            //判断是否是批量删除
            if(\$type == 2){
                \$this::destroy([\$param]);
            }else{
                \$this->where('id','in',\$param)->update(['status'=>\$type]);
            }
            return true;
        }catch(\Exception \$e){
            return false;
        }
    }

}
EOF;
        return add_dir_file($path, $name, $txt);
    }
    // 表单
    public function info_code($path, $mokuai, $html, $js)
    {
        if (empty($path) || empty($mokuai) || empty($html)) {
            return false;
        }
        $Mokuai = $mokuai;
        $name = $Mokuai . '.html';
        $x_mokuai = strtolower($Mokuai);
        $txt = <<<EOF
{$html}
<script>
{$js}
</script>
EOF;
        return add_dir_file($path, $name, $txt);
    }
    public function html_codes($table)
    {
        $columns = $this->columns($table);
        $txt = "<form class=\"layui-form\" lay-filter=\"formTest\">\n";
        $txt .= "    <input type=\"hidden\" name=\"{$this->column_name($table)}\">\n";
        $arr = ['id', 'is_del', 'create_time', 'update_time'];
        foreach ($columns as $k => $v) {
            if (!in_array($v['Field'], $arr)) {
                $comment = $v['Comment'];
                $field = $v['Field'];
                if ($v['Field'] == 'images') {
                    $txt .=
                        <<<EOF
    <div class="layui-form-item">
        <label class="layui-form-label">图片</label>
        <div class="layui-input-block">
            <div id="img_btn" style="display: flex;">
                <div class="layui-upload-drag" id="img_up">
                    <i class="layui-icon"></i>
                    <p>点击上传，或将文件拖拽到此处</p>
                    <div class="layui-hide" id="uploadDemoView">
                        <hr>
                        <img src="" alt="上传成功后渲染" style="max-width: 196px">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <div id="images"></div>
        </div>
    </div>
EOF;

                } else {
                    $txt .=
                        <<<EOF
    <div class="layui-form-item">
        <label class="layui-form-label">{$comment}</label>
        <div class="layui-input-block">
            {$this->input_type($comment,$field)}
        </div>
    </div>\n
EOF;
                }

            }
        }
        $txt .=
            <<<EOF
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="button" class="layui-btn" lay-submit lay-filter="filter">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            <button type="button" class="layui-btn layui-btn-primary" mier-event="offPopup">关闭</button>
        </div>
    </div>
</form>
EOF;
        return $txt;
    }
    public function input_type($comment, $field)
    {
        preg_match('/_id/', $field, $matches);
        $meth = str_replace($matches, '', $field);
        $arr = ['desc', 'content', 'description'];
        switch ($field) {
            case 'status':
                $txt = '<input type="checkbox" name="status" value="1" lay-skin="switch" lay-text="ON|OFF" checked="">';
                break;
            case $meth . '_id':
                $res = Db::name('auth_user')->where('status', 1)->find();
                $txt =
                    <<<EOF
<select name="{$field}" lay-search="">
                <option value=""></option>
                {volist name='info' id='vo'}
                <option value="{\$vo.id}">{\$vo.{$this->find_field($res)}}</option>
                {/volist}
            </select>
EOF;
                break;
            case in_array($field, $arr):
                $txt = "{:ue_view('{$field}')}";
                // $txt = "<textarea name=\"{$field}\" placeholder=\"请输入{$comment}内容\" class=\"layui-textarea\"></textarea>";
                break;
            default:
                $txt = "<input type=\"text\" name=\"{$field}\" placeholder=\"请输入{$comment}内容\" class=\"layui-input\">";
                break;
        }
        return $txt;
    }
    public function js_codes($table)
    {
        $js = <<<EOF
    layui.use(['form', 'jquery', 'upload', 'system'], function () {
        var form = layui.form;
        var upload = layui.upload
            , $ = layui.jquery
            , system = layui.system;
        //渲染
        var _id = getId('id');
        if (_id) {
            $.getJSON('', { id: _id }, function (res) {
                if (res.code == 200) {
                    form.val("formTest", res.data);
                    {$this->is_images($table,1)}
                    {$this->is_images($table,4)}
                }
            });
        }
        {$this->is_images($table,2)}
        form.on('submit(filter)', function (data) {
            Api_Post(data.field);
        });
    });
EOF;

        return $js;
    }
    public function is_images($table, $type)
    {
        $txt = '';
        $columns = $this->columns($table);
        $arr = array_column($columns, 'Field');
        if (in_array('images', $arr)) {
            if ($type == 1) {
                $txt = <<<EOF

                    //渲染图片
                    $.each(res.data.images.images, function (index, val) {
                        $('#images').append('<div class="imsges_lst">'
                            + '<span class="images_desc"><input name="desc[]" type="text" value="' + res.data.images.desc[index] + '"></span>'
                            + '<img src="' + val + '" height="124" width="210">'
                            + '<a href="javascript:;" class="close"><i class="layui-icon layui-icon-close"></i></a>'
                            + '<input name="images[]" type="hidden" value="' + val + '">'
                            + '</div>');
                    });
EOF;
            } elseif ($type == 2) {
                $txt = <<<EOF

        //图片上传
        upload.render({
            elem: '#img_up' //绑定元素
            , url: "{:url('Common/uploads')}" //上传接口
            , accept: 'images'
            , acceptMime: 'image/*'
            , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                layer.load(); //上传loading
            }
            , done: function (res) {
                $('#images').append('<div class="imsges_lst">'
                    + '<span class="images_desc"><input name="desc[]" type="text" value=""></span>'
                    + '<img src="' + res.data + '" height="124" width="210">'
                    + '<a href="javascript:;" class="close"><i class="layui-icon layui-icon-close"></i></a>'
                    + '<input name="images[]" type="hidden" value="' + res.data + '">'
                    + '</div>');
                layer.closeAll('loading'); //关闭loading
            }
            , error: function () {
                layer.closeAll('loading'); //关闭loading
                layer.msg('网络错误！', { icon: 5, time: 1000 });
            }
        });
        $('body').on('click', '.close', function () {
            $(this).parent().remove();
        });
EOF;
            } elseif ($type == 3) { //控制器
                $txt = "\$res['images'] = empty(\$res['images']) ? '' : unserialize(\$res['images']);";
            }
        }
        if ($type == 4) { //js富文本
            $fwb = ['desc', 'content', 'description'];
            foreach ($arr as $k => $v) {
                if (in_array($v, $fwb)) {
                    // $txt = "UE.getEditor('{$v}').setContent(res.data.{$v});";
                    $txt = "var {$v} = UE.getEditor('{$v}');";
                    $txt += "{$v}.ready(function () {{$v}.setContent(res.data.{$v});});";
                }
            }
        }
        return $txt;
    }
    public function is_type_id($table)
    {
        $txt = "return view('info');";
        $columns = $this->columns($table);
        $arr = array_column($columns, 'Field');
        foreach ($arr as $k => $v) {
            preg_match('/_id/', $v, $matches);
            if ($matches) {
                $meth = str_replace($matches, '', $v);
                $txt = <<<EOF

            \$res = Db::name('$meth')->select();
            \$info =[
                'info' => \$res
            ];
            return view('info',\$info);
EOF;
            }
        }
        return $txt;
    }
    public function find_field($data)
    {
        $res = '';
        $arr = ['name', 'title'];
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                if (in_array($k, $arr)) {
                    $res = $k;
                    break;
                }
            }
        }
        return $res;
    }
}
